package com.controller.library;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.action.library.TSetQuesAction;
import com.bean.library.DbPaper;
import com.bean.library.DbSubject;
import com.bean.library.Option;
import com.bean.library.Subject;
import com.bean.library.Teacher;
import com.bean.library.UserOption;

public class TSubmitServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4333762870720348886L;
	public void doPost(HttpServletRequest request,HttpServletResponse response){
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		DbPaper dbPaper = getDbPaper(request);
		TSetQuesAction tSetQuesAction = new TSetQuesAction();
		boolean insertResult = tSetQuesAction.setQuestion(dbPaper);
		if(insertResult){
			try {
				response.sendRedirect("/Exam1/teacher/t_page/t_welcome.jsp");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		else{
			System.out.println("插入失败");
			try {
				response.sendRedirect("/Exam1/teacher/t_page/t_setques.jsp");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	public DbPaper getDbPaper(HttpServletRequest request){
		/*************************
		 * 前台命名规则：
		 * 试卷名(Paper Name)：                            paper_name
		 * 总时间（Total Time）:       total_time                       (以小时为单位  如：2.5 小时)
		 * 总分（Total Score）：                          total_score
		 * Is Spare Exam Paper:     is_spare_paper
		 * Begin Date:              begin_date 
		 * 
		 * 
		 * Question Title:          5_title             “ 题号从1开始”
		 * Question Surface:        5_surface
		 * Question Difficulty:     5_difficulty
		 * 
		 * Option Content:          5_1_content        “ 选项号从1开始”
		 * Option RadioboxT Name:   5_1
		 * Option RadioBoxT value:  1
		 * Option RadioboxF Name:   5_1
		 * Option RadioBoxT value:  0                                                           
		 *                                                           
		 * 另外需要一个隐藏的input为course_id
		 * name="course_id"  value="1234546"
		 * 
		 * 
		**************************/
		DbPaper dbPaper = new DbPaper();
		String paperName = request.getParameter("paper_name");
		long totalTime = (long)(60*60*1000*Float.valueOf(request.getParameter("total_time")));//以毫秒为单位
		float totalScore = Float.valueOf(request.getParameter("total_score"));
		String courseId = (String)request.getSession().getAttribute("selectedCourseId");
		boolean isSparePaper = false;
		if(request.getParameter("is_spare_paper")!=null&&request.getParameter("is_spare_paper").equals("on")){
			isSparePaper = true;
		}
		Teacher teacher = (Teacher)request.getSession().getAttribute("teacher");
		String startDateStr = request.getParameter("begin_date");
		String teacherId = teacher.getTeacherId();
		float passScore = 0.6f*totalScore;//及格分数没有在页面中给出，所以在这里设置为总分的0.6
		dbPaper.setCourseId(courseId);
		dbPaper.setLastTimeMs(totalTime);
		dbPaper.setNoEnterTime(null);//这个不整了
		dbPaper.setPaperName(paperName);
		dbPaper.setPaperScore(totalScore);
		dbPaper.setPassScore(passScore);
//		Date startTime = new Date(2012-1900,12,12,12,0,0);
		
		//yyyy-MM-dd HH:MM:ss
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");//小写的mm表示的是分钟    
		System.out.println("时间字符串："+startDateStr);
		java.util.Date startTime = null;
		try {
			
			startTime = sdf.parse(startDateStr);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		System.out.println("时间转换后："+startTime);
		dbPaper.setStartTime(startTime);//!时间的获取还是一个值得商榷的问题
		//dbPaper.setStartTime(startTime)//!时间的获取还是一个值得商榷的问题
		dbPaper.setStatus(isSparePaper);//亲爱的昶老师，不知道您的status是不是这个意思
		dbPaper.setTeacherId(teacherId);
		ArrayList<Subject> submitSubjectList = new ArrayList<Subject>();
		

		System.out.println("courseId "+courseId);
		System.out.println("totalTime "+totalTime);
		System.out.println("paperName "+paperName);
		System.out.println("totalScore "+totalScore);
		System.out.println("passScore "+passScore);
		System.out.println("isSparePaper "+isSparePaper);
		System.out.println("teacherId "+teacherId);
		
		
		
		
		for(int i = 1;;i++){
			String subjectContent = request.getParameter(i+"_"+"title");
			String subjectSurface = request.getParameter(i+"_"+"surface");
			if(subjectContent==null){
				break;
			}
			//System.out.println(subjectContent+" "+request.getParameter(i+"_"+"difficulty")+" "+subjectSurface);
			int subjectDifficulty = Integer.parseInt(request.getParameter(i+"_"+"difficulty"));
			DbSubject submitSubject = new DbSubject();
			//Subject.isMulti不用写入
			submitSubject.setSubjectContent(subjectContent);
			submitSubject.setCourseId(courseId);
			submitSubject.setDifficulty(subjectDifficulty);
			submitSubject.setSurface(subjectSurface);
			ArrayList<Option> submitOptionList = new ArrayList<Option>();
			
//			System.out.println("问题信息-----");
//			System.out.println("subjectContent "+subjectContent);
//			System.out.println("courseId "+courseId);
//			System.out.println("subjectDifficulty "+subjectDifficulty);
//			System.out.println("subjectSurface "+subjectSurface);
//			System.out.println("");
//			
			
			
			
			
			
			
			for(int j = 1;;j++){
				String optContent = request.getParameter(i+"_"+j+"_"+"content");
				String optValue = request.getParameter(i+"_"+j);
				if(optContent==null){
					break; 
				}
				//System.out.println(optContent+"王一然"+optValue);
				boolean optChecked;
				if(optValue.equals("1")){
					optChecked = true;
				}
				else {
					optChecked = false;
				}
				UserOption submitOption = new UserOption();
				submitOption.setOptContent(optContent);
				submitOption.setChecked(optChecked);
				//submitOption.setFatherSubjectId(fatherSubjectId)//!由于没有插入数据库所以没有办法写入
//				submitOption.setMulti(isMulti);//这个字段没有意义
//				submitOption.setOptId(optId);//这个字段没有意义
				submitOptionList.add(submitOption);
//				
//				
//				
//				
//				System.out.println("选项信息-----");
//				System.out.println("optContent "+optContent);
//				System.out.println("optChecked "+optChecked);
//				System.out.println("");
			}
			submitSubjectList.add(submitSubject);
			submitSubject.setOptList(submitOptionList);
		}
		dbPaper.setSubjectList(submitSubjectList);
		return dbPaper;
	}
}
